package com.sxran.im.handler;

import cn.hutool.core.util.StrUtil;
import com.sxran.im.bean.MessageReqBody;
import com.sxran.im.bean.UserMessageData;
import com.sxran.im.info.ImChatBody;
import com.sxran.im.info.ImUserGroup;
import com.sxran.im.service.UserGroupService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class GetMessageCmdHandler extends GetMessageListCmdHandler{

    @Resource
    private UserGroupService userGroupService;
    @Override
    public Object doBeanService(MessageReqBody json) {
        // 执行结果
        List<ImChatBody> imChatList = (List<ImChatBody>) super.doBeanService(json);
        //
        UserMessageData userMessageData = new UserMessageData();
        Map<String, List<ImChatBody>> friends = userMessageData.getFriends();
        Map<String, List<ImChatBody>> groups = userMessageData.getGroups();
        // 私聊信息。
        for (ImChatBody imChatBody : imChatList) {
            String toId = imChatBody.getToId();
            // 好友。
            if (StrUtil.isNotEmpty(toId)) {
                List<ImChatBody> imChatBodies = friends.get(toId);
                if(imChatBodies == null){
                    imChatBodies = new ArrayList<>();
                }
                imChatBodies.add(imChatBody);
                friends.put(toId,imChatBodies);
            }

        }

        // 群聊信息。
        String userId = json.getUserId();
        List<ImUserGroup> imUserGroups = userGroupService.selectList(userId);
        for (ImUserGroup imUserGroup : imUserGroups) {
            String groupId = imUserGroup.getGid();
            // 群聊。
            if (StrUtil.isNotEmpty(groupId)) {
//                List<ImChatBody> imChatBodies = groups.get(groupId);
//                if(imChatBodies == null){
//                    imChatBodies = new ArrayList<>();
//                }
//                imChatBodies.add(imChatBody);
                MessageReqBody groupJson = new MessageReqBody();
                groupJson.setGroupId(groupId);
                List<ImChatBody> groupList = (List<ImChatBody>) super.doBeanService(groupJson);
                groups.put(groupId,groupList);
            }
        }


        return userMessageData;
    }
}
